package com.ts.api.interceptor;

import com.gitee.apanlh.spring.BeanContextUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.util.ServletUtils;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.localcache.ChannelCache;
import com.ts.api.exp.BizException;
import com.ts.api.module.channel.entity.po.ChannelPO;
import com.ts.api.module.channel.service.ChannelService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 渠道拦截器
 */
@Component
public class ChannelHandler implements HandlerInterceptor {

    private ChannelService channelService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initBean();

        String code = ServletUtils.getHeader(request, "code");
        Assert.isNotNullThrows(ValidParam.isNull(code), new BizException(BizEnum.CHANNEL_CODE_EMPTY));

        ChannelPO channelPO = ChannelCache.CHANNEL.get(code, () -> channelService.getByUniqueCode(code));
        Assert.isNotNullThrows(channelPO, new BizException(BizEnum.CHANNEL_CODE_ERROR));

        Integer enableStatus = 1;
        if (!Eq.object(enableStatus, channelPO.getStatus())) {
            Assert.isNotNullThrows(channelPO, new BizException(BizEnum.CHANNEL_DISABLE));
        }
        ChannelContext.CHANNEL.set(channelPO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ChannelContext.CHANNEL.remove();
    }

    private void initBean() {
        if (channelService == null) {
            channelService = BeanContextUtils.getBean(ChannelService.class);
        }
    }
}
